package kitwee.com.kanpad;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.inputmethodservice.KeyboardView;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.umeng.analytics.MobclickAgent;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import kitwee.com.kanpad.bean.StatusBean;
import kitwee.com.kanpad.orderDetail.SerialPortHelper;
import okhttp3.Call;
import utils.SPUtils;

/**
 * Created by sven on 2017/4/19.
 */

public class PopDialogActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.tv_username)
    TextView tvUsername;
    @BindView(R.id.tv_waring)
    TextView tvWaring;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.bt_sure)
    Button btSure;
    @BindView(R.id.bt_not_sure)
    Button btNotSure;
    @BindView(R.id.keyboard_view)
    KeyboardView keyboardView;
    @BindView(R.id.rl_keybord)
    RelativeLayout rlKeybord;
    @BindView(R.id.ll_top)
    RelativeLayout llTop;
    private Context ctx;
    private Activity act;

    private Handler sHandler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        MyMultiDexApplication.getInstance().addActivity(this);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        sHandler = new Handler();
        sHandler.post(mHideRunnable); // hide the navigation bar
        View decorView = getWindow().getDecorView();
        decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int visibility) {
                sHandler.post(mHideRunnable); // hide the navigation bar
            }
        });

//        hideBottomUIMenu();

        setContentView(R.layout.login_out_layout);
        ButterKnife.bind(this);
        ctx = this;
        act = this;

        etPassword.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return false;
            }
        });
        String user = SPUtils.getString(this, "user");
        tvUsername.setText("请输入当前账号,即可退出");
        setListener();

    }

    private void setListener() {
        btSure.setOnClickListener(this);
        btNotSure.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_sure:
                checkPassword();
                break;
            case R.id.bt_not_sure:
                hideBottomUIMenu();
                this.finish();
                break;
        }
    }

    private void loginOUt() {
        String user = SPUtils.getString(this, "user");
        String key = SPUtils.getString(this, "key");
        String kanbanNo = SPUtils.getString(this, "KANBANID");
        final long time = System.currentTimeMillis();
        String Stime = String.valueOf(time);
        final String digest = new String(Hex.encodeHex(DigestUtils.md5((key + user + time).getBytes())));
        OkHttpUtils.get()
//                .url(KanpadStrings.HOSTURL+"/kanban/unBindKanbanByNO")
                .url(BuildConfig.API_ENDPOINT + "/kanban/unBindKanbanByNO")
                .addParams("pd", digest)
                .addParams("pun", user)
                .addParams("EQ_kanban_no", kanbanNo)
                .addParams("t", Stime)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                LogUtils.e(e);

            }

            @Override
            public void onResponse(String response, int id) {
                StatusBean statusBean = JSON.parseObject(response, StatusBean.class);
                if (TextUtils.equals("200", statusBean.getStatusCode())) {
                    SPUtils.clearString(getApplicationContext(), "user");
                    SPUtils.clearString(getApplicationContext(), "pwd");
                    SPUtils.clearString(getApplicationContext(), "pwd");
                    SPUtils.clearString(getApplicationContext(), "login");
                    closeSerialPort();

//                    Intent intent = new Intent();
//                    intent.setClass(getApplicationContext(),LoginActivity.class);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
//                    startActivity(intent);
                } else if (TextUtils.equals("300", statusBean.getStatusCode())) {
                    ToastUtils.showShort("看板ID为空");
                }
//
            }
        });
    }

    private void closeSerialPort() {
        SerialPortHelper.getInstance(getApplicationContext()).closeSerialPort();
    }

    Runnable mHideRunnable = new Runnable() {
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void run() {
            int flags;
            int curApiVersion = Build.VERSION.SDK_INT;
            if (curApiVersion >= Build.VERSION_CODES.KITKAT) {
                flags =
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_IMMERSIVE
                                | View.SYSTEM_UI_FLAG_FULLSCREEN
                ;

            } else {
                flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            }

            // must be executed in main thread :)
            getWindow().getDecorView().setSystemUiVisibility(flags);
        }
    };

    private void checkPassword() {
        String password = etPassword.getText().toString();
        String pwd = SPUtils.getString(this, "user");
        if (password != null) {
            if (TextUtils.equals(password, pwd)) {

                loginOUt();
            } else {
                tvWaring.setVisibility(View.VISIBLE);
                tvWaring.setText("账户名输入错误.请重试");
            }
        }
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
